import React, { useState, forwardRef, useImperativeHandle } from 'react';
import { Form, Input, Select, Button, message } from 'antd';
import { CouponFormData } from '@/types/coupon';

interface CouponFormProps {
  onSubmit: (data: CouponFormData) => void;
  onPreview: (data: CouponFormData) => void;
}

export interface CouponFormRef {
  resetForm: () => void;
}

const CouponForm: React.ForwardRefRenderFunction<CouponFormRef, CouponFormProps> = (
  { onSubmit, onPreview },
  ref
) => {
  const [form] = Form.useForm();
  const [couponType, setCouponType] = useState<'fixed_amount' | 'discount_ratio'>('fixed_amount');

  // 暴露给父组件的方法
  useImperativeHandle(ref, () => ({
    resetForm: () => {
      form.resetFields();
    }
  }));

  const handleSubmit = async (values: CouponFormData) => {
    console.log('优惠券名字',values.name)
    console.log('优惠券类型',values.type)
    console.log('优惠券金额',values.value)
    console.log('使用门槛',values.threshold)
    console.log('有效期限',values.expireAt)
    console.log('生成数量',values.generateCount)
    console.log('适用产品',values.applicableProduct)
    console.log('优惠券描述',values.description)
    try {
      await onSubmit(values);
      // 提交后不再重置表单，因为我们现在有弹窗展示结果
      // 用户可以选择关闭弹窗后再重置表单
    } catch (error) {
      message.error('优惠券创建失败');
    }
  };

  const handlePreview = (values: CouponFormData) => {
    onPreview(values);
  };

  const handleTypeChange = (value: 'fixed_amount' | 'discount_ratio') => {
    setCouponType(value);
  };

  return (
    <Form
      form={form}
      layout="vertical"
      onFinish={handleSubmit}
      initialValues={{
        type: 'fixed_amount',
        applicableProduct: 'all_products'
      }}
    >
      <div className="grid grid-cols-2 gap-4">
        <Form.Item
          name="name"
          label="优惠券名称"
          rules={[{ required: true, message: '请输入优惠券名称' }]}
        >
          <Input placeholder="例如：新用户优惠券" />
        </Form.Item>

        <Form.Item
          name="type"
          label="优惠券类型"
          rules={[{ required: true, message: '请选择优惠券类型' }]}
        >
          <Select onChange={handleTypeChange}>
            <Select.Option value="fixed_amount">固定金额</Select.Option>
            <Select.Option value="discount_ratio">折扣百分比</Select.Option>
          </Select>
        </Form.Item>
      </div>

      <div className="grid grid-cols-2 gap-4">
        <Form.Item
          name="value"
          label={couponType === 'fixed_amount' ? "优惠金额" : "折扣百分比"}
          rules={[
            { required: true, message: couponType === 'fixed_amount' ? '请输入优惠金额' : '请输入折扣百分比' },
            {
              validator: (_, value) => {
                if (couponType === 'discount_ratio') {
                  const numValue = parseFloat(value);
                  if (numValue < 0.01 || numValue > 0.99) {
                    return Promise.reject('折扣百分比必须在0.1到0.999之间');
                  }
                }
                return Promise.resolve();
              }
            }
          ]}
        >
          <Input type="number" placeholder={couponType === 'fixed_amount' ? "例如：100" : "例如：0.85（表示85折）"} />
        </Form.Item>

        <Form.Item
          name="threshold"
          label="使用门槛 (元)"
          rules={[{ required: true, message: '请输入使用门槛' }]}
        >
          <Input type="number" placeholder="例如：200，0表示无门槛" />
        </Form.Item>
      </div>

      <div className="grid grid-cols-2 gap-4">
        <Form.Item
          name="expireAt"
          label="有效期限 (天)"
          rules={[{ required: true, message: '请输入有效期限' }]}
        >
          <Input type="number" placeholder="例如：30" />
        </Form.Item>

        <Form.Item
          name="generateCount"
          label="生成数量"
          rules={[{ required: true, message: '请输入生成数量' }]}
        >
          <Input type="number" placeholder="例如：100" />
        </Form.Item>
      </div>

      <Form.Item
        name="applicableProduct"
        label="适用产品"
        rules={[{ required: true, message: '请选择适用产品' }]}
      >
        <Select>
          <Select.Option value="all_products">所有产品</Select.Option>
          <Select.Option value="membership_package">仅限会员套餐</Select.Option>
          <Select.Option value="super_director">仅限超级编导</Select.Option>
          <Select.Option value="digital_employee">仅限数智员工</Select.Option>
          <Select.Option value="xiaorui_zhibo">仅限Know1智播</Select.Option>
        </Select>
      </Form.Item>

      <Form.Item
        name="description"
        label="描述"
      >
        <Input.TextArea rows={4} placeholder="简短描述优惠券用途和规则" />
      </Form.Item>

      <Form.Item>
        <Button type="default" onClick={() => form.validateFields().then(handlePreview)}>
          预览优惠券
        </Button>
        <Button type="primary" className="ml-2" htmlType="submit">
          生成优惠券
        </Button>
      </Form.Item>
    </Form>
  );
};

export default forwardRef(CouponForm); 